package com.menggudf.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Repository;

import com.menggudf.entity.BMIrecord;

@Repository
public class BMIrecordDao{
    
    private static final Log log = LogFactory.getLog(BMIrecordDao.class);

    @PersistenceContext(unitName = "medicalUnit")
    private EntityManager entityManager;

    public void persist(BMIrecord transientInstance) {
        try {
            entityManager.persist(transientInstance);
        } catch (RuntimeException re) {
            log.error("persist failed", re);
            throw re;
        }
    }

    public void remove(BMIrecord persistentInstance) {
        try {
            entityManager.remove(persistentInstance);
        } catch (RuntimeException re) {
            log.error("remove failed", re);
            throw re;
        }
    }

    public BMIrecord merge(BMIrecord detachedInstance) {
        try {
            BMIrecord result = entityManager.merge(detachedInstance);
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public BMIrecord findById(Integer id) {
        try {
            BMIrecord instance = entityManager.find(BMIrecord.class, id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public BMIrecord getBMIRecordLastOne(String userCode, String roleCode) {
        try {
            StringBuffer sqld = new StringBuffer("from BMIrecord b where b.userCode=?1 and b.roleCode=?2 order by createdTime desc ");
            Query query = entityManager.createQuery(sqld.toString()).setParameter(1, userCode).setParameter(2, roleCode);
            List<BMIrecord> list = query.getResultList();
            if(list!=null && list.size()>0){
                return list.get(0);
            }else{
                return null;
            }
        } catch (Exception e) {
            log.error("getBMIRecordLastOne fail",e);
        }
        return null;
    }

}
